package dao

import (
	"database/sql"
	"fmt"

	"github.com/pkg/errors"
)

const ERRNOTFOUND = 110

type PicT struct{}

func NewPicDao() *PicT {
	return &PicT{}
}

func (self *PicT) GetPicsByCid(cid int) ([]string, error) {
	var picids []string

	db, err := GetDb()
	if err != nil {
		return picids, err
	}
	defer db.Close()

	rows, err := db.Query("select picid from t_pics where cid = ? ", cid)
	if err != nil {
		err = errors.Wrap(err, fmt.Sprintf("query err:%v", cid))
		return picids, err
	}
	if errors.Is(err, sql.ErrNoRows) {
		err = ERRNOTFOUND
		return picids, err
	}

	for rows.Next() {
		var picid string
		rows.Scan(&picid)
		picids = append(picids, picid)
	}
	rows.Close()

	return picids, nil
}

//获取数据库连接
func GetDb() (*sql.DB, error) {
	db, err := sql.Open("mysql", "dataSourceName")
	if err != nil {
		err = errors.Wrap(err, fmt.Sprintf("open db failed: %v ", "dataSourceName"))
	}
	return db, err
}
